var kLeft = 1;
var kUp = 2;
var kRight = 4;
var kDown = 8;
var kSpace = 16;

var gameFocus = false;

// Bind to document key handlers.
document.onkeydown = function(e){
  if (typeof(keys) != 'undefined')
    keys.handleKeyEvent(e, true);
};
document.onkeyup = function(e){
  if (typeof(keys) != 'undefined')
    keys.handleKeyEvent(e, false);
};

function Keys() {
  this.alnum = {};
  for (var i = 0; i < 10; ++i) {
    var n = new Number(i);
    this.alnum[n.toString()] = false;
  }
  var a = "A".charCodeAt(0);
  for (var i = 0; i < 26; ++i) {
    this.alnum[String.fromCharCode(a + i)] = false;
  }
}

Keys.prototype.keyMask = 0;

/** TODO(pmy) flow should be cleaner here. */
function updateFlags(flags, mask, set) {
  return set ? flags | mask : flags & ~mask;
}

Keys.prototype.handleKeyEvent = function(event, pressed) {
  if (!event) {
    event = window.event;
  }
  if (event.keyCode == 27 && pressed && zoomed) {
    toggleZoom();
    return;
  }
  if (!gameFocus) {
    return;
  }
  switch (event.keyCode) {
  case 32: this.keyMask = updateFlags(this.keyMask, kSpace, pressed); break;
  case 37: this.keyMask = updateFlags(this.keyMask, kLeft, pressed); break;
  case 38: this.keyMask = updateFlags(this.keyMask, kUp, pressed); break;
  case 39: this.keyMask = updateFlags(this.keyMask, kRight, pressed); break;
  case 40: this.keyMask = updateFlags(this.keyMask, kDown, pressed); break;
  default:
    if ((48 <= event.keyCode && event.keyCode <= 57) ||
        (65 <= event.keyCode && event.keyCode <= 90)) {
      this.alnum[String.fromCharCode(event.keyCode)] = pressed;
    } else {
      return;
    }
    break;
  }
  event.returnValue = false;
}

Keys.prototype.spaceIsPressed = function() {
  return this.keyMask & kSpace;
}

Keys.prototype.leftIsPressed = function() {
  return this.keyMask & kLeft;
}

Keys.prototype.upIsPressed = function() {
  return this.keyMask & kUp;
}

Keys.prototype.rightIsPressed = function() {
  return this.keyMask & kRight;
}

Keys.prototype.downIsPressed = function() {
  return this.keyMask & kDown;
}

Keys.prototype.isPressed = function(k) {
  return this.alnum[k.toUpperCase().charAt(0)];
}
